package com.chenjinyan.back.service.impl;

import com.chenjinyan.back.dao.BackUserRepository;
import com.chenjinyan.back.entity.BackUserEntity;
import com.chenjinyan.back.service.BackUserService;
import com.chenjinyan.back.utils.MD5Util;
import com.chenjinyan.back.vo.BackUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

@Service
public class BackUserServiceImpl implements BackUserService {

    @Autowired
    BackUserRepository backUserRepository;


    @Override
    public int insertUser(BackUser backUser) {
        String loginAccount = backUser.getUsername();
        String password = backUser.getPassword();
        String enPassword = MD5Util.convertMD5(password);
        String phone = backUser.getPhone();
        String email = backUser.getEmail();
        String name = backUser.getName();

        List<BackUserEntity> list = backUserRepository.findByloginAccountOrPhoneOrEmail(loginAccount, phone, email);
        if (null != list && list.size() > 0) {
            //已有用户返回-1
            return -1;
        }

        return backUserRepository.insertUser(loginAccount, enPassword, phone, email, name, new Date());

    }

    @Override
    public int checkByLoginAcc(String loginAccount) throws ParseException {
        List<BackUserEntity> list = backUserRepository.findByloginAccount(loginAccount);
        if (null != list && list.size() > 0) {
            //已有用户返回-1
            return -1;
        }
        return 0;
    }

    @Override
    public int checkByPhone(String loginAccount) throws ParseException {
        List<BackUserEntity> list = backUserRepository.findByPhone(loginAccount);
        if (null != list && list.size() > 0) {
            //已有用户返回-1
            return -1;
        }
        return 0;
    }

    @Override
    public int checkByEmail(String loginAccount) throws ParseException {
        List<BackUserEntity> list = backUserRepository.findByEmail(loginAccount);
        if (null != list && list.size() > 0) {
            //已有用户返回-1
            return -1;
        }
        return 0;
    }

    @Override
    public int findByUsernameAndPassword(String username, String password) throws ParseException {
        String enPassword = MD5Util.convertMD5(password);
        List<BackUserEntity> list = backUserRepository.findByloginAccountAndPassword(username, enPassword);
        if (null != list && list.size() == 1) {
            //查询到用户返回0
            return 0;
        }
        return -1;
    }

    @Override
    public int updateLoginTime(String username) {
        return backUserRepository.updateLoginTime(username);
    }
}
